import json,os
import time
from flask import Blueprint, request, redirect, make_response, Response, jsonify
from moviepy.editor import VideoFileClip
from flask import Blueprint,request,render_template

from application.models.model import Course, Tags, course_tag,User, user_course_chapter, CourseComment, Chapter, User
from db_init import db
from swaager_init import siwa
from sqlalchemy import text
from flask_login import current_user, login_required,login_fresh
from tools.data_tools import orm2dict, ret_route, limit_offset

course_blue = siwa.blueprint("course", __name__)


@course_blue.route("/", methods=['GET'])
def course_list():
    data = dict(request.args)
    order = request.args.get('order')
    search = request.args.get('search', None)
    online = int(request.args.get('online_status', 1))
    cate = request.args.get('cate')
    tags = json.loads(request.args.get('tags', '[]'))
    limit, offset = limit_offset(data)

    # 首页四个视频
    if not order:
        data = Course.query.order_by(text('-sort_num')).limit(4).all()
        return ret_route(data=orm2dict(data))

    # 基础sql语句
    sql = Course.query.filter_by(online_status=online)

    # 传了 类型的sql
    if cate:
        sql = sql.filter_by(cate=cate)

    # 根据tags返回数据
    # join 表
    sql = sql.join(course_tag, course_tag.c.course_id == Course.id)
    if tags:
        sql = sql.filter(course_tag.c.tag_id.in_(tags))

    data = sql.order_by(text(order)).limit(limit).offset(offset * limit)

    return ret_route(data=orm2dict(data.all()))


@course_blue.route("/<int:course_id>", methods=['GET'])
def course_info(course_id):
    course = Course.query.get(course_id)
    data = orm2dict(course)
    chapters = orm2dict(course.chapters)
    data['chapters'] = chapters
    try:
        user_chapters = db.session.query(user_course_chapter) \
            .filter(user_course_chapter.c.user_id == current_user.id,
                    user_course_chapter.c.chapter_id.in_([i.id for i in course.chapters])) \
            .all()
        data['user_chapters'] = [i[0] for i in user_chapters]

        # 用户看过的所有章节
        # print(current_user.chapters)
        # print(course.chapters)
        # user_chapters = set(i.id for i in current_user.chapters) & set([i.get('id') for i in chapters])
        data['user_chapters'] = list(user_chapters)
    except AttributeError as e:
        data['user_chapters'] = []
    return ret_route(data=data)

@course_blue.route("/<int:course_id>/comment",methods=["GET"])
def course_comment(course_id):
    course = Course.query.get(course_id)
    comments_dict = {comment.id:orm2dict(comment) for comment in course.comments}
    comments = []
    for comment in comments_dict.values():
        # 根评论，添加到字典里
        if not comment['reply_id']:
            comments.append(comment)
            continue

        # 找到子评论的父级评论
        if not comments_dict[comment['reply_id']].get('son',None):
            comments_dict[comment['reply_id']]['son'] = []

        comments_dict[comment['reply_id']]['son'].append(comment)
    return ret_route(data=comments)



@course_blue.route("/<int:course_id>/<int:chapter_id>", methods=['GET'])
def get_chapter(course_id, chapter_id):
    chapter = Chapter.query.get(chapter_id)
    if login_fresh():
        current_user.bean += 10
        db.session.commit()
    return render_template('player.html', movie=orm2dict(chapter))


@course_blue.route("/<int:course_id>/chapter", methods=['POST'])
def add_chapter(course_id):
    movie = dict(request.form)
    file = request.files.get('movie')

    # 查看课程的文件夹存在否
    path = os.path.join(f'./static/movies', str(course_id))
    # 不存在新建
    if not os.path.isdir(path):
        os.mkdir(path)

    movie_path = os.path.join(path, file.filename)
    if os.path.isfile(movie_path):
        return ret_route(2004)

    file.save(movie_path)

    clip = VideoFileClip(movie_path)
    movie['duration'] = int(clip.duration)

    movie['course_id'] = course_id
    movie['path'] = movie_path[1:]
    chapter = Chapter(**movie)
    db.session.add(chapter)
    db.session.commit()
    clip.close()
    return ret_route(2000)


@course_blue.route("/collect/<int:course_id>", methods=['POST'])
@login_required
def course_collect(course_id):
    user = User.query.get(1)
    course = Course.query.get(course_id)

    # 取消收藏
    if course in user.collect_course:
        user.collect_course.remove(course)
        Course.query.filter_by(id=course_id).update({'collect_num':Course.collect_num -1})
        # commit提交
        db.session.commit()
        return ret_route(2000,msg="取消收藏成功")


    # 找用户加课程
    user.collect_course.append(course)


    # 给的课程有bug
    # 有高并发
    # Course.query.gilter_by(id=course_id).update({"collect_num":course.collect_num + 1})



    # 已解决
    Course.query.gilter_by(id=course_id).update({"collect_num":Course.collect_num + 1})
    db.session.commit()
    return ret_route(2000)


